<?php
class TBB_Auth_Adapter2 implements Zend_Auth_Adapter_Interface
{
	const NOT_FOUND_MSG = 'Account not found';
	const BAD_PW_MSG = 'Password is invalid';

	/**
	 * 
	 * @var Zend_Db_Table_Row_Abstract
	 */
	protected $_user;
	
	/**
	 * 
	 * @var string
	 */
	protected $_username = "";
	
	/**
	 * 
	 * @var string
	 */
	protected $_password = ""; 
	
	/**
	 * 
	 * @var Zend_Db_Table_Row_Abstract
	 */

	
	public function __construct($username, $password)
	{
		$this->_username = $username;
		$this->_password = $password;
	}
	
	/**
	 * Authenticate the user logged in
     * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
     * @return Zend_Auth_Result
	 */
	public function authenticate()
	{
		try {
			$userModel = new TBB_Model_Users();
			$this->_user = $userModel->authenticate($this->_username, $this->_password);		
			return $this->_createResult(Zend_Auth_Result::SUCCESS);
		}
		catch(Exception $e) {
			if($e->getMessage() == TBB_Model_Users::WRONG_PW) {
				return $this->_createResult(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array(self::BAD_PW_MSG));				
			}
			if($e->getMessage() == TBB_Model_Users::NOT_FOUND) {
				return $this->_createResult(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, array(self::NOT_FOUND_MSG));				
			}			
		}
	}	
	
	private function _createResult($code, $messages = array())
	{
		
		return new Zend_Auth_Result($code, $this->_user, $messages); 
	}
}